package com.example.a2306_shop.search

import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.a2306_shop.R
import com.example.a2306_shop.adapter.ProductAdapter
import com.example.a2306_shop.databinding.ActivitySearchBinding
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.room.AppDbUtils
import com.example.lib_base.room.HistoryEntity
import com.google.android.material.chip.Chip
import java.util.Timer
import java.util.TimerTask

@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<ActivitySearchBinding,SearchViewModel>() {

    lateinit var productAdapter: ProductAdapter
    val list = mutableListOf("口红","茶叶","运动鞋","衬衣")
    var index = 0//显示下标
    lateinit var timer: Timer
    val handler = Handler()
    override fun initData() {
        viewModel.productSuccess.observe(this){
            if(it.code==200){
                productAdapter.data.clear()
                productAdapter.data.addAll(it.data.list)
                productAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
        timer = Timer()
        timer.schedule(object :TimerTask(){
            override fun run() {
                //实现轮播
                binding.sv.queryHint = list[index]
                index++
                if(index==list.size){
                    index=0
                }
            }
        },0,2000)



        productAdapter = ProductAdapter()
        binding.rvProduct.adapter = productAdapter
        binding.rvProduct.layoutManager = GridLayoutManager(this,2)

        //默认不展示任何数据  当输入关键词后显示
        binding.sv.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                //点击回车键调用查询方法
                if(query!=null){
                    viewModel.search(query,10,1)
                    //保存历史搜索记录
                    AppDbUtils.getAppDb().getHistoryDao().insert(HistoryEntity(query))
                    //实时更新历史记录
                    queryHis()
                }
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                //当文字发生变化后，调用查询方法
                if(newText!=null){
                    viewModel.search(newText,10,1)
                }
                return true
            }
        })
        //进入界面 先查询历史搜索记录    当查询完成后，显示历史搜索记录
        queryHis()
        //点击清空历史记录  删除数据库中的所有数据 并清空界面
        binding.tvDelete.setOnClickListener {
            AppDbUtils.getAppDb().getHistoryDao().deleteAll()
            binding.cg.removeAllViews()
        }
        //模拟 淘宝 关键词自动轮播
    }

    private fun queryHis() {
       //查询历史记录
        val list = AppDbUtils.getAppDb().getHistoryDao().query()
        list.reverse()//倒序
        if(list.isNotEmpty()){
            binding.cg.removeAllViews()//移除之前的历史搜索记录
            list.forEach {
                //数据循环创建对应的chip
                val chip = LayoutInflater.from(this).inflate(R.layout.item_cg, null) as Chip
                //Chip中的文字要发生变化
                chip.findViewById<TextView>(R.id.name).text = it.keyword

                binding.cg.addView(chip)
                //点击实现再次查询
                chip.setOnClickListener {it1->
                    binding.sv.setQuery(it.keyword,true)
                }
                //点击删除图标，从数据库中删除
                chip.setOnCloseIconClickListener {it2->
                    //删除数据库    从页面删除
                    AppDbUtils.getAppDb().getHistoryDao().delete(it)
                    binding.cg.removeView(it2)
                }

            }
        }
    }

    override fun getViewModel(): Class<SearchViewModel> = SearchViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_search
    //防止内存泄露
    override fun onDestroy() {
        super.onDestroy()
        //当页面被销毁时
        timer.cancel()
    }

}